<template>
    <div>
        <el-form label-width="110px" size="small">
            <el-row class="form-row">
                <el-col :span="12">
                    <el-form-item label="产品代码:" v-if="isBatchStock">
                        <RiskEntryInput @set-entry-data="getEntryslist" :returnDatas="instruction.fundCode" />
                    </el-form-item>
                    <el-form-item label="组合编码:" v-if="isBatchStock">
                        <el-select
                            v-model="instruction.fundAccountCode"
                            @change="handleChange(instruction.fundAccountCode, 'fundAccountCode')"
                            size="mini"
                        >
                            <el-option
                                v-for="i in computedFundAccountCodeSelectData"
                                :key="i.fundAccountCode"
                                :label="i.fundAccountCode + ' ' + i.fundAccountName"
                                :value="i.fundAccountCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="证券代码:" v-if="isBatchFund">
                        <el-select
                            v-model="instruction.stockCode"
                            @change="handleStockCode"
                            filterable
                            @visible-change="handleStockVisibleChange"
                            :filter-method="getstockCodeList"
                            :loading="selectLoading"
                            size="mini"
                            clearable
                            @clear="getstockCodeList('')"
                        >
                            <el-option v-for="i in stockCodeSelectData" :key="i.dictKey" :label="i.dictKey + ' ' + i.dictKeyName" :value="i.dictKey">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="业务类型:">
                        <el-select v-model="instruction.businClass" size="mini" disabled>
                            <el-option label="债券一级市场" value="D"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="委托方向:">
                        <el-select v-model="instruction.orderDirection" size="mini" disabled :class="['font-color-' + 'red']">
                            <el-option label="分销买入" value="K"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="投标方式:" v-if="isBatchFund">
                        <el-select v-model="instruction.tenderWay" size="mini">
                            <el-option label="一级缴款" value="1"> </el-option>
                            <el-option label="上市买入" value="2"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="招标标的:" v-if="isBatchFund">
                        <el-select v-model="instruction.subject" size="mini" disabled>
                            <el-option v-for="i in subjectSelectData" :key="i.value" :label="i.label" :value="i.value"> </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="投标方式:" v-if="isBatchStock">
                        <el-select v-model="instruction.tenderWay" size="mini">
                            <el-option label="一级缴款" value="1"> </el-option>
                            <el-option label="上市买入" value="2"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if="instruction.subject === '' || instruction.subject === '3'" label="价格:">
                        <RiskInputNumber
                            style="margin-top: 3px"
                            :input="instruction.orderPrice"
                            :inputAfter="'元'"
                            :colorStyle="textColor"
                            :precision="2"
                            :maxlength="15"
                            :field="'orderPrice'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item v-else label="利率:">
                        <RiskInputNumber
                            style="margin-top: 3px"
                            :input="instruction.orderPrice"
                            :inputAfter="'%'"
                            :precision="2"
                            :maxlength="15"
                            :field="'orderPrice'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="投标金额:">
                        <RiskInputNumber
                            :input="instruction.orderBalance"
                            :inputAfter="'万元'"
                            :colorStyle="textColor"
                            :precision="4"
                            :maxlength="15"
                            :field="'orderBalance'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="上市日期" v-if="isBatchFund">
                        <el-date-picker
                            disabled
                            v-model="instruction.listDate"
                            type="date"
                            format="yyyy-MM-dd"
                            value-format="yyyyMMdd"
                            style="width: 100%"
                            placeholder="请选择"
                        ></el-date-picker>
                    </el-form-item>
                    <el-form-item label="缴款日期" v-if="isBatchFund">
                        <el-date-picker
                            disabled
                            v-model="instruction.payDate"
                            type="date"
                            format="yyyy-MM-dd"
                            value-format="yyyyMMdd"
                            style="width: 100%"
                            placeholder="请选择"
                        ></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script lang="ts">
import Invest from '@/common/dict/invest';
import { objToArr, SGU_CACHE } from '@/utils/diction-const-util';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import { SelectOptionItemData } from '@/pages/risk-time/types/SelectOptionItemData';
import RiskEntryInput from '@/common/components/risk-entry-input.vue';

@Component({
    name: 'PrimaryBondBidForm',
    components: {
        RiskInputNumber,
        RiskEntryInput,
    },
})

// 场外基金指令
export default class PrimaryBondBidForm extends Vue {
    @Prop()
    detail: any;
    @Prop()
    renderCount: number;
    @Prop()
    selectStockInfo: any;
    @Prop()
    isBatchFund: boolean; // 多基金指令
    @Prop()
    isBatchStock: boolean; // 多基金指令

    Invest: any = new Invest();
    selectLoading: boolean = false; // 下拉框远程搜索时的加载状态
    fundCodeSelectData: any[] = []; // 产品序号下拉框数据
    fundAccountCodeSelectData: any[] = []; // 组合编码下拉框数据
    // allStockType: any[] = [];
    orderDirectionSelectData: any[] = []; // 订单方向下拉框数据
    subjectSelectData: any[] = [
        {
            value: '1',
            label: '利率',
        },
        {
            value: '3',
            label: '价格',
        },
    ]; // 招标标的下拉框数据

    businessSelectData: SelectOptionItemData[] = [];

    investPriceSelectData: any[] = []; // 价格模式下拉框数据
    stockCodeSelectData: any[] = []; // 证券代码下拉框数据

    orderAmountStatus: boolean = false;
    orderBalanceStatus: boolean = false;

    private instruction = {
        fundCode: '', // 产品代码
        fundAccountCode: '', // 组合编码
        reportCode: '', // 申报代码
        orderDirection: 'K', // 委托方向
        marketCode: '',
        stockCode: '', // 证券代码
        businClass: 'D',
        orderAmount: '', // 指令数量
        orderPrice: '', // 指令价格
        orderBalance: '', // 指令金额
        // fundNameSt: '',
        // fundAccountName: '',
        subject: '', // 招标标的
        // stockFaceBalance: '',
        referencedYield: '0', // 参考收益率
        listDate: '',
        payDate: '',
        tenderWay: '1', // 招标方式
    };
    stockInfo: any = {};
    textColor: string = 'red';

    async mounted() {
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfo', '/fundInfo/list', []);
        // 获取组合编码下拉框数据
        let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });
        // 获取价格模式下拉框数据
        this.investPriceSelectData = await SGU_CACHE('PriceType', '/dict/list/code/Y_000237', []);
        // 获取证券代码下拉框数据
        this.getstockCodeList('');
    }

    @Watch('instruction', { immediate: true, deep: true })
    setValues() {
        this.$emit(
            'handleSettingValue',
            {
                ...this.instruction,
                orderBalance: Number(this.instruction.orderBalance || '0') * 10000,
            },
            '10'
        );
    }

    @Watch('selectStockInfo', { immediate: true, deep: true })
    onWatchStockInfo() {
        if (this.selectStockInfo && Object.keys(this.selectStockInfo).length) {
            this.instruction.stockCode = this.selectStockInfo?.stockCode;
            this.instruction.reportCode = this.selectStockInfo?.reportCode || this.instruction.stockCode.split(' ')[0];
            this.instruction.marketCode = this.selectStockInfo?.marketCode;
            this.instruction.listDate = String(this.selectStockInfo?.listDate);
            this.instruction.payDate = String(this.selectStockInfo?.payDate);
            if (this.selectStockInfo.bidObject) {
                this.instruction.subject = this.selectStockInfo.bidObject;
            } else {
                this.instruction.subject = '3';
            }
            // 给 价格 || 利率 赋上默认值
            if (this.instruction.subject === '' || this.instruction.subject === '3') {
                this.instruction.orderPrice = '100';
            } else {
                this.instruction.orderPrice = '1';
            }
            this.getstockCodeList(this.selectStockInfo.stockCode);
        } else {
            this.instruction.stockCode = '';
            this.instruction.orderPrice = '';
            this.instruction.listDate = '';
            this.instruction.payDate = '';
        }
    }

    // 监听 组合编码计算属性 (每当计算属性变动时 自动选中第一项)
    @Watch('computedFundAccountCodeSelectData', { immediate: true, deep: true })
    watchcomputedFundAccountCode(newData) {
        if (newData && newData.length) {
            this.instruction.fundAccountCode = newData[0].fundAccountCode;
        }
    }

    @Watch('renderCount', { immediate: true, deep: true })
    async setForm() {
        if (this.detail && Object.keys(this.detail).length) {
            let instruction = this.detail;
            // 获取组合编码下拉框数据
            let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
            arr.forEach(item => {
                this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
            });

            for (const key in instruction) {
                this.instruction[key] = instruction[key];
            }
            this.instruction.orderBalance = (Number(this.instruction.orderBalance || 0) / 10000).toString();
            await this.getstockCodeList(this.detail.stockCode);

            let stock = this.stockCodeSelectData.find(item => item.dictKey === this.detail.stockCode);

            if (stock && stock.bondInfo) {
                this.stockInfo = stock.bondInfo;
                this.stockInfo.stockNameSt = stock.dictKeyName;
                this.instruction.reportCode = this.stockInfo.reportCode;
                this.instruction.marketCode = this.stockInfo.marketCode;
                this.instruction.listDate = this.stockInfo.listDate;
                this.instruction.payDate = this.stockInfo.payDate;
                if (this.stockInfo.bidObject) {
                    this.instruction.subject = this.stockInfo.bidObject;
                } else {
                    this.instruction.subject = '3';
                }
            }
        }
    }

    get computedFundAccountCodeSelectData(): any {
        return this.fundAccountCodeSelectData[this.instruction.fundCode];
    }

    getInputNumber(args: any) {
        let value = args[0];
        let field = args[1];
        this.instruction[field] = value;
    }

    getEntryslist(val: any) {
        this.instruction.fundCode = val;
        this.handleFundCodeChange(val);
    }

    handleFundCodeChange(val: string): void {
        let fund = this.fundCodeSelectData.find(item => item.fundCode === val) || {};
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || [])[0] || {};
        // this.instruction.fundNameSt = fund.fundNameSt;
        this.instruction.fundAccountCode = fundAccount.fundAccountCode;
        // this.instruction.fundAccountName = fundAccount.fundAccountName;
    }

    handleFundAccountCodeChange(value: string) {
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || []).find(item => item.fundAccountCode === value) || {};
        // this.instruction.fundAccountName = fundAccount.fundAccountName;
    }

    handleStockCode(stockCode: string): void {
        this.stockInfo = {};
        this.instruction.reportCode = '';
        this.instruction.marketCode = '';
        this.instruction.listDate = '';
        this.instruction.payDate = '';
        this.instruction.subject = '';
        this.instruction.orderPrice = '';
        this.instruction.orderBalance = '';
        if (stockCode) {
            let stock = this.stockCodeSelectData.find(item => item.dictKey === stockCode);
            if (stock && stock.bondInfo) {
                this.stockInfo = stock.bondInfo;
                this.stockInfo.stockNameSt = stock.dictKeyName;
                this.instruction.reportCode = this.stockInfo.reportCode;
                this.instruction.marketCode = this.stockInfo.marketCode;
                this.instruction.listDate = this.stockInfo.listDate;
                this.instruction.payDate = this.stockInfo.payDate;
                if (this.stockInfo.bidObject) {
                    this.instruction.subject = this.stockInfo.bidObject;
                } else {
                    this.instruction.subject = '3';
                }
                // 给 价格 || 利率 赋上默认值
                if (this.instruction.subject === '' || this.instruction.subject === '3') {
                    this.instruction.orderPrice = '100';
                } else {
                    this.instruction.orderPrice = '1';
                }
            }
            // this.$emit('getStockInfo', this.stockInfo);
        }
        this.$emit('getStockInfo', this.stockInfo);
    }

    handleStockVisibleChange(val) {
        if (!val) {
            this.getstockCodeList('');
        }
    }

    // 获取证券代码下拉框数据
    async getstockCodeList(val: string | undefined) {
        this.selectLoading = true;
        await this.$axios
            .post('/dict/bond/select', {
                bondInfo: {
                    bidTag: 1,
                },
                dictKey: val,
                dictKeyName: val,
            })
            .then((res: any) => {
                this.stockCodeSelectData = res || [];
                this.selectLoading = false;
            });
    }
}
</script>
<style lang="scss" scoped>
.form-row {
    margin-top: 3px;
    .el-form-item--small {
        margin: 0;
        & /deep/ .el-form-item__label {
            color: #575757;
        }
        & /deep/ .el-input__inner {
            height: 28px;
            line-height: 28px;
        }
        .font-color-red {
            /deep/ input {
                color: red !important;
            }
            /deep/ .el-input-group__append {
                color: red !important;
            }
        }
    }
}
</style>
